<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>
<!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-message" class="ml-5" v-model="email"></el-input>-->
<!--      <el-input style="width: 200px" placeholder="请输入" suffix-icon="el-icon-position" class="ml-5" v-model="address"></el-input>-->
      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
      <!-- <el-upload action="http://localhost:9090/homestays/import" :show-file-list="false" accept="xlsx" :on-success="handleExcelImportSuccess" style="display: inline-block">
        <el-button type="primary" class="ml-5">导入 <i class="el-icon-bottom"></i></el-button>
      </el-upload>
      <el-button type="primary" @click="exp" class="ml-5">导出 <i class="el-icon-top"></i></el-button> -->
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
      <el-table-column prop="address" label="详细地址"></el-table-column>
      <el-table-column prop="area" label="所在地区"></el-table-column>
      <el-table-column prop="summary" label="描述" width="180" >
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.description" placement="top">
            <span>{{ scope.row.description ? scope.row.description.substring(0, 30) + '...' : '' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="180" ><template slot-scope="scope" ><el-image style="width: 100px; height: 100px" :src="scope.row.img" :preview-src-list="[scope.row.img]"></el-image></template></el-table-column>
      <el-table-column prop="name" label="民宿名称"></el-table-column>
      <el-table-column prop="price" label="每晚价格"></el-table-column>
      <el-table-column prop="rating" label="评分"></el-table-column>
      <el-table-column prop="rules" label="入住规则" width="180" ></el-table-column>
      <el-table-column prop="time" label="创建时间"></el-table-column>
      <el-table-column prop="type" label="民宿类型：别墅、公寓、木屋等"></el-table-column>
      <el-table-column prop="updatedAt" label="更新时间"></el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="280" align="center">
        
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i></el-button>
          <el-button type="primary" @click="handleViewImages(scope.row)">查看图片 <i class="el-icon-picture"></i></el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
      <el-form label-width="120px" size="small" style="width: 80%; margin: 0 auto">
        <el-form-item prop="address" label="详细地址">
          <el-input v-model="form.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="area" label="所在地区">
          <el-input v-model="form.area" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="bathrooms" label="浴室数量">
          <el-input v-model="form.bathrooms" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="bedrooms" label="卧室数量">
          <el-input v-model="form.bedrooms" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="beds" label="床位数量">
          <el-input v-model="form.beds" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="capacity" label="容纳人数">
          <el-input v-model="form.capacity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="description" label="描述">
          <el-input type="textarea" v-model="form.description" autocomplete="off" :rows="4"></el-input>
        </el-form-item>
        
        <el-form-item prop="img" label="封面">
          <el-upload action="http://localhost:9090/file/upload" ref="img" :on-success="handleImgUploadSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="image" label="更多图片">
          <el-upload
            action="http://localhost:9090/file/upload"
            list-type="picture-card"
            ref="multipleImg"
            :on-success="handleMultipleImgUploadSuccess"
            :on-remove="handleMultipleImgRemove"
            :file-list="form.imageList || []"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item prop="name" label="民宿名称">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="price" label="每晚价格">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="rating" label="评分">
          <el-input v-model="form.rating" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="reviewCount" label="评价数量">
          <el-input v-model="form.reviewCount" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="rules" label="入住规则">
          <el-input v-model="form.rules" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="状态：0-下架，1-上架">
          <el-input v-model="form.status" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="type" label="民宿类型：别墅、公寓、木屋等">
          <el-input v-model="form.type" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新增的图片管理对话框 -->
    <el-dialog title="图片管理" :visible.sync="imagesDialogVisible" width="60%" :close-on-click-modal="false">
      <div v-if="currentHomestay" class="image-manager">
        <h3>{{ currentHomestay.name }} 的图片</h3>
        
        <div class="image-upload-section">
          <h4>上传新图片</h4>
          <el-upload
            action="http://localhost:9090/file/upload"
            list-type="picture-card"
            :on-success="handleImageDialogUploadSuccess"
            :on-preview="(file) => handlePictureCardPreview(file.url)"
            :file-list="[]"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>

        <div class="image-list-section">
          <h4>当前图片</h4>
          <div class="image-grid" v-if="homestayImages && homestayImages.length">
            <div v-for="img in homestayImages" :key="img.id" class="image-item">
              <div class="image-cover-badge" v-if="img.isCover === 1">封面</div>
              <el-image 
                :src="img.img" 
                fit="cover" 
                class="homestay-image"
                :preview-src-list="homestayImages.map(item => item.img)"
                @click="handlePictureCardPreview(img.img)"
              ></el-image>
              <div class="image-actions">
                <el-tooltip content="删除" placement="top">
                  <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeImage(img.id)"></el-button>
                </el-tooltip>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无图片"></el-empty>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="imagesDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="pictureDialogVisible">
      <img width="100%" :src="pictureDialogImageUrl" alt="预览图片">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Homestays",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      form: {
        imageList: []
      },
      dialogFormVisible: false,
      multipleSelection: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      // 新增的数据
      imagesDialogVisible: false,
      currentHomestay: null,
      pictureDialogVisible: false,
      pictureDialogImageUrl: '',
      originalImages: [],
      // 新增图片表相关数据
      homestayImages: [],
      coverImage: null,
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.request.get("/homestays/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    save() {
      this.request.post("/homestays", this.form).then(res => {
        if (res.code === '200') {
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        } else {
          this.$message.error("保存失败")
        }
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {
        imageList: []
      }
      this.$nextTick(() => {
        if(this.$refs.img) {
           this.$refs.img.clearFiles()
        }
        if(this.$refs.multipleImg) {
           this.$refs.multipleImg.clearFiles()
        }
      })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      if (this.form.image && Array.isArray(this.form.image)) {
        this.form.imageList = this.form.image.map(url => ({
          name: url.split('/').pop(),
          url: url
        }))
      } else {
        this.form.imageList = []
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if(this.$refs.img) {
          this.$refs.img.clearFiles()
        }
        if(this.$refs.multipleImg) {
          this.$refs.multipleImg.clearFiles()
        }
      })
    },
    del(id) {
      this.request.delete("/homestays/" + id).then(res => {
        if (res.code === '200') {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择需要删除的数据")
        return
      }
      let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
      this.request.post("/homestays/del/batch", ids).then(res => {
        if (res.code === '200') {
          this.$message.success("批量删除成功")
          this.load()
        } else {
          this.$message.error("批量删除失败")
        }
      })
    },
    reset() {
      this.name = ""
      this.load()
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    handleFileUploadSuccess(res) {
      this.form.file = res
    },
    handleImgUploadSuccess(res) {
      this.form.img = res
    },
    handleMultipleImgUploadSuccess(res, file) {
      if (!this.form.image) {
        this.form.image = []
      }
      this.form.image.push(res)
      if (!this.form.imageList) {
        this.form.imageList = []
      }
      this.form.imageList.push({
        name: file.name,
        url: res
      })
    },
    handleMultipleImgRemove(file) {
      const index = this.form.imageList.findIndex(item => item.url === file.url)
      if (index > -1) {
        this.form.image.splice(index, 1)
        this.form.imageList.splice(index, 1)
      }
    },
    download(url) {
      window.open(url)
    },
    exp() {
      window.open("http://localhost:9090/homestays/export")
    },
    handleExcelImportSuccess() {
      this.$message.success("导入成功")
      this.load()
    },
    handleStatusChange(row) {
      this.request.post("/homestays/status", {
        id: row.id,
        status: row.status
      }).then(res => {
        if (res.code === '200') {
          this.$message.success("状态更新成功")
          this.load()
        } else {
          this.$message.error("状态更新失败")
          // 如果更新失败，恢复原来的状态
          row.status = row.status === 1 ? 0 : 1
        }
      })
    },
    // 修改后的方法
    handleViewImages(row) {
      this.currentHomestay = JSON.parse(JSON.stringify(row))
      this.homestayImages = []
      this.coverImage = null
      
      // 从图片表获取当前民宿的所有图片
      this.request.get("/homestayImages/list", {
        params: {
          homestayId: row.id
        }
      }).then(res => {
        if (res.code === '200') {
          this.homestayImages = res.data || []
          
          // 查找封面图片
          const cover = this.homestayImages.find(img => img.isCover === 1)
          if (cover) {
            this.coverImage = cover
          }
          
          this.imagesDialogVisible = true
        } else {
          this.$message.error("获取图片失败")
        }
      })
    },
    handleImageDialogUploadSuccess(res) {
      // 上传新图片后，添加到图片表
      this.request.post("/homestayImages", {
        homestayId: this.currentHomestay.id,
        img: res,
        isCover: 0  // 默认非封面
      }).then(response => {
        if (response.code === '200') {
          this.$message.success("图片上传成功")
          // 重新加载图片列表
          this.handleViewImages(this.currentHomestay)
        } else {
          this.$message.error("图片上传失败")
        }
      })
    },
    removeImage(imageId) {
      // 删除图片
      this.request.delete("/homestayImages/" + imageId).then(res => {
        if (res.code === '200') {
          this.$message.success("图片删除成功")
          // 重新加载图片列表
          this.handleViewImages(this.currentHomestay)
        } else {
          this.$message.error("图片删除失败")
        }
      })
    },
    handlePictureCardPreview(imageUrl) {
      this.pictureDialogImageUrl = imageUrl
      this.pictureDialogVisible = true
    },
    saveImages() {
      // 关闭对话框，由于所有操作都是实时执行的，这里不需要额外保存
      this.imagesDialogVisible = false
      // 刷新民宿列表
      this.load()
    }
  }
}
</script>


<style>
.headerBg {
  background: #eee!important;
}

/* 新增的样式 */
.image-manager {
  padding: 10px;
}

.image-manager h3 {
  margin-bottom: 20px;
  color: #303133;
}

.image-manager h4 {
  margin: 15px 0;
  color: #606266;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 5px;
}

.image-upload-section {
  margin-bottom: 20px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.image-item {
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
  padding-bottom: 35px;
}

.homestay-image {
  width: 100%;
  height: 160px;
  display: block;
}

.image-cover-badge {
  position: absolute;
  top: 5px;
  left: 5px;
  background-color: #67C23A;
  color: white;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
  z-index: 1;
}

.image-actions {
  position: absolute;
  bottom: 5px;
  right: 5px;
  display: flex;
  gap: 5px;
}

.image-actions .el-button {
  transform: scale(0.9);
}
</style>
